﻿using System;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using ZilLion.Service.Core.Domain.EntityBase;
using ZilLion.Service.WeChatMall.Domain.Entitys.Orders;
using ZilLion.Service.WeChatMall.Domain.Repositorys.Interface.CrmProxy;
using ZilLion.Service.WeChatMall.Domain.Repositorys.Interface.Order;
using ZilLion.Service.WeChatMall.Domain.Requests;
using ZilLion.Service.WeChatMall.Domain.Requests.CrmProxy;
using ZilLion.Service.WeChatMall.Domain.Responses;
using ZilLion.Service.WeChatMall.Domain.Services.Interface;

namespace ZilLion.Service.WeChatMall.Controllers
{
    /// <summary>
    ///     微商城订单功能
    /// </summary>
    [Route("Api/WechatMall/Order")]
    public class OrderController : WechatMallControllerBase
    {
        private readonly ICrmProxyRepository _crmProxyRepository;
        private readonly IOrderDiscountReponsitory _orderDiscountReponsitory;
        private readonly IOrderService _orderService;

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="orderDiscountReponsitory"></param>
        /// <param name="orderService"></param>
        /// <param name="crmProxyRepository"></param>
        public OrderController(IOrderDiscountReponsitory orderDiscountReponsitory, IOrderService orderService,
            ICrmProxyRepository crmProxyRepository)
        {
            _orderDiscountReponsitory = orderDiscountReponsitory;
            _orderService = orderService;
            _crmProxyRepository = crmProxyRepository;
        }

        /// <summary>
        ///     获取折后价格和积分信息
        /// </summary>
        [HttpPost("GetOrderDiscount")]
        public OrderDiscountResponse GetOrderDiscount([FromBody] OrderDiscountRequest request, string token = null)
        {
            var result = _orderDiscountReponsitory.GetDiscountResult(request.DiscountTypeId, request.OrderGoods);
            return new OrderDiscountResponse {Result = result};
        }

        /// <summary>
        ///     保存未支付订单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("SavePrePayOrder")]
        [HttpPost]
        public OrderResponse SavePrePayOrder([FromBody] PrePayOrderRequest request, string token = null)
        {
  
            var dto = _orderService.SavePrePayOrder(request.Order);
            return new OrderResponse {Order = dto};
        }

        /// <summary>
        ///     获取订单列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("GetPrePayOrderList")]
        [HttpGet]
        public OrderAbstractListResponse GetPrePayOrderList(string token = null)
        {
            var custid = GetCustId();
            return new OrderAbstractListResponse {List = _orderService.GetPrePayOrdersAbstract(custid)};
        }


        /// <summary>
        ///     获取订单列表
        /// </summary>
        /// <param name="minsno">当前已加载最大的sno</param>
        /// <param name="count">本次加载的数量</param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("GetOrderList")]
        [HttpGet]
        public OrderAbstractListResponse GetOrderList(int count = 5, string minsno = "", string token = null)
        {
            var custid = GetCustId();
            var list = _orderService.GetOrdersAbstract(custid, count, minsno);

            return new OrderAbstractListResponse {List = list};
        }

        /// <summary>
        ///     现金支付订单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("CashPayOrder")]
        [HttpPost]
        public OrderResponse CashPayOrder([FromBody] OrderRequest request, string token = null)
        {
            var now = DateTime.Now.GetNowChinaTime();

            #region 构造付款请求体

            var payRequest = new CrmCashPayRequest {YwCore = new Ywcore(), YwInfo = new Ywinfo()};
            payRequest.YwCore.Oprcardno = GetPassport();
            payRequest.YwCore.Oprctype = (short) PassportType.WeChatAppidAndOpenid;
            payRequest.YwCore.Oprtime = new DateTime(now.Year, now.Month, now.Day);
            payRequest.YwCore.Oprbrname = request.Order.MainInfo.Shopname;
            payRequest.YwCore.Oprxfje = request.Order.MainInfo.TotalMy;

            payRequest.YwInfo.Oprywsno = request.Order.MainInfo.Sno;
            payRequest.YwInfo.Oprywdate = new DateTime(now.Year, now.Month, now.Day);

            payRequest.YwInfo.Oprywwindow = "微商城线上";
            payRequest.YwInfo.Oprywbno = request.Order.MainInfo.Bno;

            #endregion


            var payResult = _crmProxyRepository.CashPay(payRequest, GetPassport(), GetCrmApiGetWay(),
                PassportType.WeChatAppidAndOpenid);

            if (payResult != null && payResult.Errormodel == null && payResult.Description.IsNullOrEmpty())
            {
                var dto = _orderService.CashPay(payResult, request.Order, request.AccInfo, GetPassport(),
                    PassportType.WeChatAppidAndOpenid, GetCrmApiGetWay());
                return new OrderResponse {Order = dto};
            }

            if (payResult != null && payResult.Description.IsNotNullOrEmpty())
                return new OrderResponse {Errormodel = new WebErrorModel {ErrMessage = payResult.Description}};

            return payResult?.Errormodel != null
                ? new OrderResponse {Errormodel = new WebErrorModel {ErrMessage = payResult.Errormodel.desc}}
                : new OrderResponse {Errormodel = new WebErrorModel {ErrMessage = "微信卡支付遇到未知问题!"}};
        }

        /// <summary>
        ///     根据SNO 支付
        /// </summary>
        /// <param name="sno"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("CashPayOrderBySno")]
        [HttpPost]
        public OrderAbstractResponse CashPayOrderBySno(string sno, string token = null)
        {
            var now = DateTime.Now.GetNowChinaTime();
            var order = _orderService.GetPrePayOrderBySno(sno);
            var passport = GetPassport();

            #region 构造付款请求体

            var payRequest = new CrmCashPayRequest {YwCore = new Ywcore(), YwInfo = new Ywinfo()};
            payRequest.YwCore.Oprcardno = passport;
            payRequest.YwCore.Oprctype = 2;
            payRequest.YwCore.Oprtime = new DateTime(now.Year, now.Month, now.Day);
            payRequest.YwCore.Oprbrname = order.MainInfo.Shopname;
            ;
            payRequest.YwCore.Oprxfje = order.MainInfo.TotalMy;

            payRequest.YwInfo.Oprywsno = order.MainInfo.Sno;
            payRequest.YwInfo.Oprywdate = new DateTime(now.Year, now.Month, now.Day);

            payRequest.YwInfo.Oprywwindow = "微商城线上";
            payRequest.YwInfo.Oprywbno = order.MainInfo.Bno;

            #endregion

            var accinfo =
                _crmProxyRepository.GetAccInfo(passport, GetCrmApiGetWay(), PassportType.WeChatAppidAndOpenid);
            var payResult = _crmProxyRepository.CashPay(payRequest, passport, GetCrmApiGetWay(),
                PassportType.WeChatAppidAndOpenid);
            if (payResult != null && payResult.Errormodel == null && payResult.Description.IsNullOrEmpty())
            {
                var completedto = _orderService.CashPay(payResult, order, accinfo.AccInfo, passport,
                    PassportType.WeChatAppidAndOpenid, GetCrmApiGetWay());
                return new OrderAbstractResponse {Order = new OrderAbstractDto(completedto)};
            }


            if (payResult != null && payResult.Description.IsNotNullOrEmpty())
                return new OrderAbstractResponse {Errormodel = new WebErrorModel {ErrMessage = payResult.Description}};

            return payResult?.Errormodel != null
                ? new OrderAbstractResponse {Errormodel = new WebErrorModel {ErrMessage = payResult.Errormodel.desc}}
                : new OrderAbstractResponse {Errormodel = new WebErrorModel {ErrMessage = "微信卡支付遇到未知问题!"}};
        }


        /// <summary>
        /// </summary>
        /// <param name="sno"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("CancelOrderBySno")]
        [HttpPost]
        public ResponseBase CancelOrderBySno(string sno, string token = null)
        {
            _orderService.CancelOrderBySno(sno);
            return new ResponseBase();
        }

        /// <summary>
        ///     根据订单号获取订单信息
        /// </summary>
        /// <param name="sno">订单号</param>
        /// <param name="billtype">单据类型,1-已支付,0-未支付</param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("GetOrderBySno")]
        [HttpGet]
        public OrderResponse GetOrderBySno(string sno, short billtype, string token = null)
        {
            if (billtype == 0)
            {
                var dto = _orderService.GetPrePayOrderBySno(sno);
                return new OrderResponse {Order = dto};
            }
            else
            {
                var dto = _orderService.GetPiedOrderBySno(sno);
                return new OrderResponse {Order = dto};
            }
        }
    }
}